#!/usr/bin/env python3
"""
调试ChromaDB metadata问题
"""

import sys
import os
import django

# 设置Django环境
sys.path.append('/Users/baimu/PycharmProjects/2505A/boss-llm/boss')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boss.settings')
django.setup()

def debug_metadata_issue():
    """
    调试metadata问题
    """
    print("=" * 80)
    print("调试ChromaDB metadata问题")
    print("=" * 80)
    
    try:
        from rag.job_recommendation.job_recommendation import fetch_job, build_searchable_text_from_job
        
        print("1. 检查原始数据...")
        job_list = fetch_job(limit=3)
        
        for i, job in enumerate(job_list, 1):
            print(f"\n岗位 {i}:")
            print(f"  ID: {job.get('id')}")
            print(f"  标题: '{job.get('title', '')}'")
            print(f"  公司: '{job.get('company', '')}'")
            print(f"  城市: '{job.get('city', '')}'")
            print(f"  学历: '{job.get('education', '')}'")
            print(f"  标签: '{job.get('tags', '')}'")
            print(f"  工作经验: '{job.get('working', '')}'")
            print(f"  工作年限: '{job.get('working_years', '')}'")
            
            # 检查字段是否存在
            print(f"  字段检查:")
            print(f"    title存在: {'title' in job}")
            print(f"    company存在: {'company' in job}")
            print(f"    city存在: {'city' in job}")
            print(f"    education存在: {'education' in job}")
            print(f"    tags存在: {'tags' in job}")
            print(f"    working存在: {'working' in job}")
            print(f"    working_years存在: {'working_years' in job}")
            
            # 检查字段值
            print(f"  值检查:")
            print(f"    title值: {repr(job.get('title', 'NOT_FOUND'))}")
            print(f"    company值: {repr(job.get('company', 'NOT_FOUND'))}")
            print(f"    city值: {repr(job.get('city', 'NOT_FOUND'))}")
            
        print("\n2. 检查构建的搜索文本...")
        for i, job in enumerate(job_list, 1):
            job_str = build_searchable_text_from_job(job)
            print(f"\n岗位 {i} 搜索文本:")
            print(job_str[:200] + "..." if len(job_str) > 200 else job_str)
            
    except Exception as e:
        print(f"❌ 调试失败: {str(e)}")
        import traceback
        traceback.print_exc()


def check_chroma_storage():
    """
    检查ChromaDB存储
    """
    print("\n" + "=" * 80)
    print("检查ChromaDB存储")
    print("=" * 80)
    
    try:
        import chromadb
        
        client = chromadb.PersistentClient(path="./chromadb_db")
        collection = client.get_collection(name="job_text_embedding_0927")
        
        # 获取几个样本文档
        sample = collection.get(limit=3, include=["metadatas", "documents"])
        
        if sample and sample.get("metadatas"):
            print("样本文档metadata:")
            for i, metadata in enumerate(sample["metadatas"]):
                print(f"\n文档 {i+1}:")
                print(f"  metadata类型: {type(metadata)}")
                print(f"  metadata内容: {metadata}")
                if metadata:
                    print(f"  metadata键: {list(metadata.keys())}")
                    for key, value in metadata.items():
                        print(f"    {key}: '{value}' (类型: {type(value)})")
                else:
                    print("  metadata为空")
        else:
            print("❌ 无法获取样本文档")
            
    except Exception as e:
        print(f"❌ 检查失败: {str(e)}")


def main():
    """
    主函数
    """
    print("开始调试metadata问题...")
    
    debug_metadata_issue()
    check_chroma_storage()
    
    print("\n调试完成！")


if __name__ == "__main__":
    main()
